package org.wevil.exception;

import org.wevil.enumu.ResultEnum;
import org.wevil.vo.Result;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.UnexpectedTypeException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Web异常处理
 * */
@RestControllerAdvice
public class WebExceptionHandler {

    /** 方法参数验证异常 */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> messages = new ArrayList<>();
        allErrors.forEach(error -> messages.add(error.getDefaultMessage()));
        String message = Collections.singletonList(messages).toString();
        message = message.replace("[", "");
        message = message.replace("]", "");
        return Result.info(ResultEnum.ERROR, message);
    }

    /** 类型不对异常 */
    @ExceptionHandler(value = UnexpectedTypeException.class)
    public Result<String> UnexpectedTypeException(UnexpectedTypeException e){
        String message = e.getMessage();
        return Result.info(ResultEnum.ERROR, message);
    }

    /** http消息不可读异常 */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result<String> HttpMessageNotReadableException(HttpMessageNotReadableException e){
        String message = e.getMessage();
        return Result.info(ResultEnum.ERROR, message);
    }

    /** 唯一判断异常 */
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public Result<String> SQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        return Result.info(ResultEnum.ERROR, message);
    }
}
